<template>
  <div class="app-container">
    <el-form class="query-wrapper" :model="queryParams" style="display: block;">
      <el-date-picker type="daterange" start-placeholder="Start date" end-placeholder="End date"
      format="YYYY-MM-DD" v-model="dateValue" style="width: 220px;" /> 
      &nbsp;&nbsp; 
      <el-select
        v-model="queryParams.vesselName"
        filterable
        clearable
        placeholder="Vessel"
        style= "width: 160px;">
        <el-option :key="item" :label="item" :value="item" v-for="item in vessels">
        </el-option>
      </el-select> 
      &nbsp;&nbsp; 
      <el-select v-model="queryParams.voyageNo" style="width: 160px;" filterable clearable placeholder="Voyage">
        <el-option :key="item" :label="item" :value="item" v-for="item in voyages">
        </el-option>
      </el-select> 
      &nbsp;&nbsp; 
      <el-select v-model="queryParams.pol" style="width: 150px;" filterable clearable allow-create placeholder="POL">
         <el-option :key="item" :label="item" :value="item" v-for="item in pols">
          </el-option>
    </el-select>
       &nbsp;&nbsp;
      <el-select v-model="queryParams.pod" style="width:150px;" filterable clearable allow-create placeholder="POD">
        <el-option :key="item" :label="item" :value="item" v-for="item in pods">
        </el-option>
      </el-select>  &nbsp;&nbsp;
     
    <el-row style="margin-top: 10px;">
      <el-select v-model="queryParams.fuelType" filterable clearable allow-create placeholder="Fuel Type">
        <el-option v-for="item in fuel_type" :key="item.label" :label="item.label" :value="item.label" />
      </el-select>
      &nbsp;&nbsp; &nbsp;&nbsp;
      <el-select v-model="queryParams.cargoType" filterable clearable allow-create placeholder="Cargo Type">
        <el-option v-for="item in cargo_type" :key="item.label" :label="item.label" :value="item.label" />
      </el-select>
      &nbsp;&nbsp; &nbsp;&nbsp;
      <el-select v-model="queryParams.shipper" filterable clearable allow-create placeholder="Shipper">
        <el-option v-for="item in shippers" :key="item" :label="item" :value="item" />
      </el-select>
      &nbsp;&nbsp;&nbsp;&nbsp;
      <el-button type="primary"  icon="search" @click="search">Search</el-button>&nbsp;&nbsp;
      <SearchReset :query-params="queryParams" @reset="resetQuery"></SearchReset> &nbsp;&nbsp;&nbsp;&nbsp;
      <el-button type="success" plain icon="upload" v-hasPermi="['summary:import']" @click="uploadFileForm">Import</el-button>
      <!-- <el-button type="primary" plain icon="upload" onclick="this.nextSibling.click()">Upload</el-button>
        <input
          id="upload-spec-file"
          type="file"
          accept=".xlsx"
          v-show="false"
          @change="uploadFile($event)"
		       v-hasPermi="['cargoList:upload']"
        /> -->
        &nbsp;&nbsp;
    <el-button type="warning" icon="download" v-hasPermi="['summary:export']" v-if="listData.length >0" @click="handlePrint">Export</el-button>
    </el-row>
    </el-form>

    <!-- </div> -->
    <el-empty v-if="listData.length === 0" description="No Data" :image-size="100" />
    <div v-for="(item, index) in listData" :key="index" class="item-box">
      <h3 style="text-align: center;display: flex;justify-content: center;">
        <el-input   v-if="isEdit&&editIndex === index&&editType=='title'" style="width: 30%;" v-model="item.title"></el-input>
        <strong v-else  >{{item.title}}</strong>
        <span style="margin-left: 10px;">
          <el-icon>
            <Finished v-if="isEdit&&editIndex === index&&editType=='title'"  @click="editTitle(false,index,'title')" /> 
            <Edit v-else @click="editTitle(true,index,'title')" />
          </el-icon>
        </span>
      </h3>
      <el-row class="manifest-tip-item__wrapper">
        <el-col :span="6" class="manifest-tip-item">
          <el-input   v-if="isEdit&&editIndex === index&&editType=='titlePol'"  style="width: 60%;" v-model="item.polDetail"></el-input>
          <span class="title" v-else><strong >POL：</strong>{{item.polDetail }}</span>
          <span style="margin-left: 10px;">
          <el-icon>
            <Finished v-if="isEdit&&editIndex === index&&editType=='titlePol'"  @click="editTitle(false,index,'titlePol')" /> 
            <Edit v-else @click="editTitle(true,index,'titlePol')" />
          </el-icon>
        </span>
        </el-col>
        <el-col :span="6" class="manifest-tip-item">
          <el-date-picker value-format="YYYY-MM-DD" v-if="isEdit&&editIndex === index&&editType=='date'" style="width: 60%;"  v-model="item.cargoDate"/> 
          <span class="title" v-else><strong>Date：</strong>{{ item.cargoDate }} </span>
          <span style="margin-left: 10px;">
            <el-icon>
              <Finished v-if="isEdit&&editIndex === index&&editType=='date'"  @click="editTitle(false,index,'date')" /> 
              <Edit v-else @click="editTitle(true,index,'date')" />
            </el-icon>
          </span>
        </el-col>   
      </el-row>
      <el-table :ref="el => (tableRefs[index] = el)" stripe :data="item.detail" style="width: 100%" :border="true" :show-overflow-tooltip="true"
        @sort-change="handleSortChange">        
        <el-table-column prop="channel" label=" Channel" width="150" align="center" />
        <el-table-column prop="collectionFrom" label="Collection From" width="150" align="center" />
        <el-table-column prop="shipper" label="Shipper" width="100"  show-overflow-tooltip align="center"/>
        <el-table-column prop="model" label="Model"   width="100"  show-overflow-tooltip align="center"/>
        <el-table-column prop="pol" label="POL" width="130" align="center">
          <template #default={row,$index}>
            <el-input   v-if="row.id != null && isEdit&&editIndex === index&&editType=='pol'&&rowIndex==$index" style="width: 60%;" v-model="row.pol"></el-input>
            <span class="title" v-else>{{row.pol }}</span>
            <span style="margin-left: 10px;" v-if="$index!=item.detail.length-1">
              <el-icon>
                <Finished v-if="row.id != null && isEdit&&editIndex === index&&editType=='pol'&&rowIndex==$index"  @click="editTitle(false,index,'pol',$index)" /> 
                <Edit v-else @click="editTitle(true,index,'pol',$index)" />
              </el-icon>
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="pod" label="POD"   width="130"  align="center">
          <template #default={row,$index}>
            <el-input   v-if="row.id != null&& isEdit&&editIndex === index&&editType=='pod'&&rowIndex==$index"  style="width: 60%;" v-model="row.pod"></el-input>
            <span class="title" v-else>{{row.pod }}</span>
            <span style="margin-left: 10px;" v-if="$index!=item.detail.length-1">
              <el-icon>
                <Finished v-if="row.id != null && isEdit&&editIndex === index&&editType=='pod'&&rowIndex==$index"  @click="editTitle(false,index,'pod',$index)" /> 
                <Edit v-else @click="editTitle(true,index,'pod',$index)" />
              </el-icon>
            </span>
          </template>
        </el-table-column> 
        <el-table-column prop="maker" label="MAKER"   width="140"  align="center" />
        <el-table-column prop="cargoType" label="Cargo Type"   width="200"  show-overflow-tooltip align="center" />
        <el-table-column prop="fuelType" label="Fuel Type"   width="100" show-overflow-tooltip  align="center"/>
        <el-table-column prop="measureLength" label="Length(m)"   width="100" show-overflow-tooltip align="center"/>
        <el-table-column prop="measureWidth" label="Width(m)" width="100" show-overflow-tooltip align="center"/>
        <el-table-column prop="measureHeight" label="Width(m)" width="100" show-overflow-tooltip align="center"/>
        <el-table-column prop="totalUnits" label="total units" width="100" show-overflow-tooltip align="center" />
        <el-table-column prop="unitWeight" label="Unit Weight" width="100" show-overflow-tooltip align="center"/>
        <el-table-column prop="totalVolume" label="Total CBM" width="100" show-overflow-tooltip align="center"/>
        <el-table-column prop="rate" label="Rate" width="100"  align="center"/>
        <el-table-column prop="revenue" label="Revenue" width="100"  align="center"/> 
        <el-table-column prop="clientRate" label="Client Rate" width="120"  align="center" />
        <el-table-column prop="clientRevenue" label="Client Revenue" width="120" align="center" />
        <el-table-column prop="profit" label="Profit" width="100"/>           
        <el-table-column prop="status" label="Status"   width="120" />  
        <el-table-column prop="remark" label="Remarks"   show-overflow-tooltip/>
        <el-table-column label="Operation" v-hasPermi="['summary:edit']" width="110" fixed="right"> 
      <template #default="scope">
        <span class="btn-primary" v-if="scope.row.id != null" @click="editClickEvent(scope.row)">{{ $t("ship.button.edit") }}</span
        >&nbsp;&nbsp;
        <span class="btn-primary"  v-if="scope.row.id != null"  @click="removeClickEvent(scope.row.id)">{{ $t("ship.button.remove") }}</span> 
      </template>
    </el-table-column>
      </el-table>
    </div>
    <pagination
    v-show="total > 0"
    :total="total"
    :page="queryParams.pageNum"
    :limit="queryParams.pageSize"
    @pagination="pageQuery"
    style="float: right"
  />

    <el-dialog width="900" destroy-on-close draggable :title="dialogTitle" v-model="dialogFormVisible">
      <el-form :model="formParam" :rules="rules" ref="custForm">
        <el-row>
          <el-col :span="12">
            <el-form-item label="Channel" label-width="120px" prop="channel" >
              <el-input  v-model="formParam.channel"></el-input>
            </el-form-item>
          </el-col>
        
          <el-col :span="12">
            <el-form-item label="Collect From" label-width="120px" prop="collectionFrom" >
              <el-input  v-model="formParam.collectionFrom"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="Shipper" label-width="120px" prop="shipper" required>
              <el-input v-model="formParam.shipper" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="Model" label-width="120px" prop="model" required>
              <el-input v-model="formParam.model" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="POL" label-width="120px" prop="pol" required>
              <el-input v-model="formParam.pol" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="POD" label-width="120px" prop="pod" required>
              <el-input v-model="formParam.pod" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="MAKER" label-width="120px" prop="maker" >
              <el-input v-model="formParam.maker" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="Cargo Type" label-width="120px" prop="cargoType" required>
              <el-select v-model="formParam.cargoType" filterable clearable allow-create style="width: 100%;">  
              <el-option v-for="item in cargo_type" :key="item.label" :label="item.label" :value="item.label" />
            </el-select> 
            </el-form-item>
          </el-col>
          <el-col :span="8">
          <el-form-item label="Fuel Type" label-width="120px" prop="fuelType" required>
            <el-select v-model="formParam.fuelType" filterable clearable allow-create>
              <el-option v-for="item in fuel_type" :key="item.label" :label="item.label" :value="item.label" />
            </el-select>
          </el-form-item>
        </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="Length(m)" label-width="120px" prop="measureLength" required>
              <el-input-number v-model="formParam.measureLength" :prcesion="3" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="Width(m)" label-width="120px" prop="measureWidth" required>
              <el-input-number v-model="formParam.measureWidth" :prcesion="3" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="Height(m)" label-width="120px" prop="measureHeight" required>
              <el-input-number v-model="formParam.measureHeight" :prcesion="3" />
            </el-form-item>
        </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="Total CBM" label-width="120px" prop="totalVolume" required>
              <el-input-number :presion="3" v-model="formParam.totalVolume" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="Rate" label-width="120px" prop="rate" required>
              <el-input-number v-model="formParam.rate" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="Revenue" label-width="120px" prop="revenue" required>
              <el-input v-model="formParam.revenue" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
         
          <el-col :span="8">
            <el-form-item label="Client Rate" label-width="110px" prop="clientRate">
              <el-input-number v-model="formParam.clientRate"  />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="Client Revenue" label-width="120px" prop="clientRevenue" >
              <el-input-number :model-value="computedValue" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="Profit" label-width="120px" prop="profit" >
              <el-input v-model="formParam.profit" readonly/>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row>
          <el-col :span="24">
            <el-form-item label="REMARKS" label-width="220px" prop="remark">
              <el-input type="textarea" v-model="formParam.remark"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">{{ $t("ship.button.cancel") }}</el-button>
          <el-button @click="resetForm" type="warning">{{ $t("ship.button.reset") }}</el-button>
          <el-button type="primary" @click="submitForm">{{ $t("ship.button.submit") }}</el-button>
        </span>
      </template>
    </el-dialog>
    <FileUpload ref="fileUploadRef" :url="downTemplateUrl" :templateFile="templateFile" :isAlink="false" :queryParams="queryParams" :uploadFileUrl="uploadFileUrl" :fileType="fileType" @update:modelValue="updateFileUpload"  />
  </div>
</template>   
  <script lang="ts" setup name="summary">
  import { ref, onMounted, reactive,computed } from "vue";  
  import service from "@/utils/request";  
  import { ElNotification, ElMessageBox } from "element-plus";    
  import { convertDate } from "@/utils/date" 
  import { downloadFile } from "@/utils/downloadFile";
  import { useTablesDrag } from '@/hooks/useHooks';
  const { proxy, tableRefs, initTableDrag } = useTablesDrag()
  let cargo_type = reactive([])
  const custForm = ref(null);
  const dialogTitle = ref("");
  const initForm = {
    id: null,
    title:null,
    polDetail:null,
    cargoDate:null,
    collectionFrom:null,
    status: null,
    channel:null,
    shipper: null,
    collectFrom: null,
    pol:null,
    pod:null,
    maker:null,
    model: null,
    cargoDesc: null,
    cargoType: null,
    fuelType: null,
    measureLength: null,
    measureWidth: null,
    measureHeight: null,
    unitCbm: null,
    unitWeight: null,
    rate:null,
    revenue:null,
    totalUnits: null,
    totalVolume: null,
    totalWeight: null,
    clientRate: null,
    profit:null,
    remark:null
  };
  
  const formParam = reactive(Object.assign({}, initForm));

  // 导入功能
  const fileUploadRef = ref(null)
  const templateFile=ref('summary.xlsx')
  const uploadFileForm = () => {
  proxy.$refs["fileUploadRef"].dialogUploadFileForm()
  }
  const uploadFileUrl = "/shipping/forwardCargo/uploadFile"
  const downTemplateUrl=ref('shipping/forwardCargo/download/template')
  const fileType=ref(['.xlsx','.xls'])
  const updateFileUpload= (data: any) => {
  refreshTable();
  };

  const total = ref(0);
  let fuel_type = reactive([])
  const rules = ref({}); 
  let vessels = reactive([] as any)
  let voyages = reactive([] as any)
  let pols = reactive([] as any)
  let pods = reactive([] as any)
  let shippers = reactive([] as any)
  const dateValue = ref([new Date('2025-01-18'), new Date()])
  const queryParams = reactive({
    pageNum: 1,
    pageSize: 20,
    vesselName:null,
    voyageNo:null, 
    pol:null,
    pod:null,
    startDate: convertDate(dateValue.value[0]),
    endDate: convertDate(dateValue.value[1]),
    fuelType:null,
    shipper:null,
    cargoType:null,
    orderByColumn: undefined,
    isAsc: undefined,
  });
  
  const listData = ref([]);
  const refreshTable = async () => {
    if(dateValue.value != null){  
      queryParams.startDate = convertDate(dateValue.value[0])
      queryParams.endDate = convertDate(dateValue.value[1]) 
    }else{
       queryParams.startDate= null
       queryParams.endDate= null
    } 

    let result = await service.get("/shipping/forwardCargo/getTable", { params: queryParams });
    listData.value = result.data;
    total.value = result.total 
    initTableDrag()
  };
  
  const isEdit=ref(false)
  const editIndex=ref<number|null>(null)
  const rowIndex=ref<number|null>(null)
  const editType=ref<string|null>(null)
  const editTitle = async(item:any,index:number,type:string,$index:number) => {
    isEdit.value=item
    editIndex.value= index 
    rowIndex.value=$index
    editType.value=type
  
    if(!item){
          ElMessageBox.confirm("Confirm to edit the data？", "Confirmation Information", {
      type: "warning",
      confirmButtonText: "Confirm",
      cancelButtonText: "Cancel",
    }).then(async () => {
        let rs=listData.value[index];
        
        // Object.keys(initForm).forEach((k) => (formParam[k] = initForm[k]));
        formParam.title=rs.title
        formParam.id=rs.detail[0]['id']
        formParam.polDetail=rs.polDetail
        formParam.cargoDate=rs.cargoDate
        formParam.detail=rs.detail
        await service.put("/shipping/forwardCargo/updateTitle", formParam );

        // @ts-ignore
        ElNotification.success({
          title: "Prompt information",
          message: "save successful!",
          position: "bottom-right",
        });
      })
    }
  };
  const dialogFormVisible = ref(false);
  
  const editClickEvent = (row: any) => {
    dialogTitle.value = "Update Summary";
    dialogFormVisible.value = true;
    isAdd = false;
    Object.keys(initForm).forEach((k) => (formParam[k] = row[k]));
  };
  
  let isAdd = false;
  
  const addClickEvent = () => {
    dialogTitle.value = "Add Forwarding Cargo";
    isAdd = true;
    dialogFormVisible.value = true;
  
    Object.assign(formParam, initForm);
  };  
  
  const resetForm = () => {
    // @ts-ignore
    custForm.value.resetFields();
  };
  
  const submitForm = () => {
    // @ts-ignore
    custForm.value.validate(async (valid) => {
      if (!valid) {
        return;
      }    
      
      await service[isAdd ? "post" : "put"]("shipping/forwardCargo", formParam);
      // @ts-ignore
      ElNotification.success({
        title: "Prompt information",
        message: "save successful!",
        position: "bottom-right",
      });
      dialogFormVisible.value = false;
      refreshTable();
    });
  };
  
  const pageQuery = async (e) => {
    queryParams.pageNum = e.page;
    queryParams.pageSize = e.limit;
    refreshTable();
  };
  
  const search = () => {
    refreshTable();
  };
   
  const resetQuery = (data:any) => {
    Object.assign(queryParams, data)
    listData.value = []
    total.value = 0
  }
  
  const uploadFile = async (event) => {
    if (event.target == null || event.target.files[0] == null) {
      return;
    }
    const formData = new FormData();
    formData.append("file", event.target.files[0]);
    await service["post"]("shipping/forwardCargo/uploadFile", formData);
  };
  
  const handleSortChange = async (column: any) => {
    queryParams.orderByColumn = column.prop;
    queryParams.isAsc = column.order; //动态取值排序顺序
    refreshTable();
  };
  
  const computedValue = computed(() => {
  if (formParam.clientRate !=null) {
      let result = (formParam.clientRate * formParam.totalVolume).toFixed(3)
      formParam.profit = formParam.revenue - result
      return result
    }  
    return null
});
  const removeClickEvent = (id) => {
    ElMessageBox.confirm("Confirm to Remove the data？", "Confirmation Information", {
      type: "warning",
      confirmButtonText: "Confirm",
      cancelButtonText: "Cancel",
    }).then(async () => {
      await service.delete(`shipping/forwardCargo/${id}`);
  
      refreshTable();
      // @ts-ignore
      ElNotification.success({
        title: "Prompt information",
        message: "Delete successfully!",
        position: "bottom-right",
      });
    });
  };

  const handlePrint =()=>{
    downloadFile("/shipping/forwardCargo/export", queryParams,"forward.xlsx")
  }
  
  onMounted(async () => { 
    service.get("/shipping/forwardCargo/getQueryCond").then(res=>{
      vessels = res.data.vessel
      voyages = res.data.voyage
      pols = res.data.pol
      pods = res.data.pod
      shippers = res.data.shipper
      dateValue.value = [new Date(res.data.startDate), new Date(res.data.endDate)] 
    })
    const res  = await proxy.useDict("cargo_type","fuel_type");
    cargo_type = res.cargo_type
    fuel_type = res.fuel_type 
    //refreshTable();
  });
  </script>
  <style lang="scss" scoped>
  .el-table__expand-column .cell {
      display: block !important;
  }
  .mytable th{
  border:#333 !important;
  
  }
.item-box{
  padding: 24px;
}
.manifest-tip-item__wrapper{
  margin-bottom: 12px;
}
  </style>